package com.cy.lib.redis.demo.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.management.MXBean;

import org.springframework.stereotype.Repository;

import com.cy.lib.redis.core.annotation.CacheClass;
import com.cy.lib.redis.core.annotation.CacheDelete;
import com.cy.lib.redis.core.annotation.CacheList;
import com.cy.lib.redis.core.annotation.CacheList.TYPE;
import com.cy.lib.redis.core.annotation.CacheOnly;
import com.cy.lib.redis.core.annotation.CacheSave;
import com.cy.lib.redis.core.annotation.CacheUpdate;
import com.cy.lib.redis.demo.domain.DoMainPersistence;
import com.cy.lib.redis.demo.domain.User;

@Repository
@CacheClass(nameSpace = "user")
public class UserDao {

	@CacheSave(key = "#user.userId.toString()")
	public User saveUser(User user){
		DoMainPersistence.userMap.put(user.getUserId(), user);
		return user;
	}
	
	@CacheList(listType = TYPE.ALL, objCls = User.class , objKey = "#user.userId.toString()")
	public List<User> findAll(){
		List<User> list = new ArrayList<User>(DoMainPersistence.userMap.values());
		System.out.println("从数据库查询");
		return list;
	}
	
	@CacheList(listType = TYPE.CONDITION,
				objCls = User.class ,
				objKey = "#user.userId.toString()" ,
				condition = "local str = redis.call('HGET', KEYS[1],'userName'); return str=='李四';"
			)
	public List<User> findByName(String userName){
		Map<Long,User> map = DoMainPersistence.userMap;
		List<User> list = new ArrayList<User>();
		for(User e:map.values()){
			if(userName.equals(e.getUserName())){
				list.add(e);
			}
		}
		System.out.println("从数据库查询");
		return list;
	}
	
	@CacheOnly(keys = "#id.toString()",columns="id")
	public User findById(long id){
		User user = DoMainPersistence.userMap.get(id);
		System.out.println("从数据库查询");
		return user;
	}
	
	@CacheUpdate(key = "#user.userId.toString()")
	public User updateUser(User user){
		DoMainPersistence.userMap.put(user.getUserId(), user);
		return user;
	}
	
	@CacheDelete(key = "#user.userId.toString()")
	public void delUser(User user){
		DoMainPersistence.userMap.remove(user.getUserId());
	}
}
